import os
import sys
import time
import signal
import subprocess
import psutil
from python_redis import PythonRedis

class RedisServer:
    def __init__(self):
        self.pid_file = "redis_server.pid"
        self.log_file = "redis_server.log"
        self.process = None

    def start(self):
        """启动Redis服务器"""
        if self.is_running():
            print("Redis服务器已经在运行中")
            return False
        
        try:
            # 启动服务器进程
            with open(self.log_file, 'w') as log:
                # 直接运行python_redis.py文件
                self.process = subprocess.Popen(
                    [sys.executable, 'python_redis.py'],
                    stdout=log,
                    stderr=log,
                    cwd=os.getcwd()  # 设置工作目录
                )
            
            # 保存PID
            with open(self.pid_file, 'w') as f:
                f.write(str(self.process.pid))
            
            # 等待服务器启动
            max_wait = 10  # 最多等待10秒
            wait_interval = 0.5  # 每0.5秒检查一次
            waited = 0
            
            while waited < max_wait:
                if self.is_running():
                    # 检查日志文件，确认服务器是否真正启动
                    with open(self.log_file, 'r') as log:
                        content = log.read()
                        if "Redis server successfully started" in content:
                            print("Redis服务器启动成功")
                            return True
                        elif "Failed to start server" in content:
                            print("Redis服务器启动失败，请检查日志文件")
                            self.stop()
                            return False
                time.sleep(wait_interval)
                waited += wait_interval
            
            # 如果超时，尝试停止进程
            self.stop()
            print("Redis服务器启动超时，请检查日志文件")
            return False
            
        except Exception as e:
            print(f"启动失败: {e}")
            return False

    def stop(self):
        """停止Redis服务器"""
        if not self.is_running():
            print("Redis服务器未运行")
            return False
        
        try:
            # 读取PID
            with open(self.pid_file, 'r') as f:
                pid = int(f.read())
            
            # 终止进程
            process = psutil.Process(pid)
            process.terminate()
            
            # 等待进程结束
            max_wait = 5
            waited = 0
            wait_interval = 0.1
            
            while waited < max_wait:
                if not psutil.pid_exists(pid):
                    break
                time.sleep(wait_interval)
                waited += wait_interval
            
            # 如果进程还在运行，强制终止
            if psutil.pid_exists(pid):
                process.kill()
            
            # 清理PID文件
            if os.path.exists(self.pid_file):
                os.remove(self.pid_file)
            
            print("Redis服务器已停止")
            return True
        except Exception as e:
            print(f"停止失败: {e}")
            return False

    def restart(self):
        """重启Redis服务器"""
        if self.is_running():
            self.stop()
            time.sleep(1)  # 等待进程完全停止
        return self.start()

    def is_running(self):
        """检查服务器是否在运行"""
        if not os.path.exists(self.pid_file):
            return False
        
        try:
            with open(self.pid_file, 'r') as f:
                pid = int(f.read())
            return psutil.pid_exists(pid)
        except:
            return False

    def status(self):
        """显示服务器状态"""
        if self.is_running():
            print("Redis服务器正在运行")
        else:
            print("Redis服务器未运行")

def main():
    if len(sys.argv) != 2:
        print("用法: python run_server.py [start|stop|restart|status]")
        sys.exit(1)

    server = RedisServer()
    command = sys.argv[1].lower()

    if command == "start":
        server.start()
    elif command == "stop":
        server.stop()
    elif command == "restart":
        server.restart()
    elif command == "status":
        server.status()
    else:
        print("无效的命令。可用命令: start, stop, restart, status")
        sys.exit(1)

if __name__ == "__main__":
    main()